const toggleBtn = document.querySelectorAll('.zl');
const detailModal = document.getElementById('detailModal');
const closeBtn = document.getElementById('closeBtn');
const followButton = document.getElementById('follow');
const followButtons = document.getElementById('follows');

// 显示详细信息
if (toggleBtn.length > 0 && detailModal && closeBtn) {
    // 遍历所有匹配的按钮，为每个按钮添加点击事件监听器
    toggleBtn.forEach(function (button) {
        button.addEventListener('click', function () {
            if (detailModal.style.display === 'none' || detailModal.style.display === '') {
                detailModal.style.display = 'block';
                this.textContent = '收起详细信息';
                document.body.classList.add('modal-open');
            } else {
                detailModal.style.display = 'none';
                this.textContent = '显示详细信息';
                document.body.classList.remove('modal-open');
            }
        });
    });
    closeBtn.addEventListener('click', function () {
        detailModal.style.display = 'none';
        // 遍历所有按钮，将文本重置为显示详细信息
        toggleBtn.forEach(function (button) {
            button.textContent = '显示详细信息';
        });
        document.body.classList.remove('modal-open');
    });
}

const clickableItems = document.querySelectorAll('.icon1.action-item.clickable');
clickableItems.forEach(item => {
    item.addEventListener('click', function () {
        this.classList.toggle('clicked');
    });
});
const mask=document.querySelector('.mask')
const titleInput = document.getElementById('titleInput');
const titleCharCount = document.getElementById('titleCharCount');
const contentTextarea = document.getElementById('contentTextarea');
const contentCharCount = document.getElementById('contentCharCount');
const closeButton = document.getElementById('closeButton');


// 获取所有的 "read-full-text" 元素和 "top-story-content-detail-list-p" 元素
const read_full_texts = document.getElementsByClassName('read-full-text');
const top_story_content_detail_list_ps = document.getElementsByClassName('empty');

// 遍历所有的 "read-full-text" 元素并添加点击事件监听器
for (let i = 0; i < read_full_texts.length; i++) {
    read_full_texts[i].addEventListener('click', function() {
        const index = Array.from(read_full_texts).indexOf(this);
        const targetParagraph = top_story_content_detail_list_ps[index];
        const user_information=document.getElementsByClassName('user-information')[index];
        const empty=document.getElementsByClassName('empty')[index]
        const user_name=document.getElementsByClassName('user-name')[index]
        const contentright=contentrights[index]
        const top_story_content_detail_list=top_story_content_detail_lists[index]
        // 使用 window.getComputedStyle 获取元素的实际样式
        const currentHeight = window.getComputedStyle(targetParagraph).height;
        if (currentHeight === '49px') {
            targetParagraph.style.height = 'auto';
            targetParagraph.style.display= 'block';
            user_information.style.display='block';
            user_name.style.display='none'
            empty.classList.add('content')
            contentright.style.display='none'
            console.log(contentright.style.display)
            console.log( user_information.style.display)
            console.log(1)
            top_story_content_detail_list.style.width='100%'
            this.innerHTML = '<i class="iconfont">&#xe60d;</i>收起<i class="iconfont">&#xe6b8;</i>';
        } else {
            targetParagraph.style.height = '49px';
            this.innerHTML = '<i class="iconfont">&#xe60d;</i>阅读全文<i class="iconfont">&#xe7d1;</i>';
            targetParagraph.style.display= '-webkit-box';
            user_information.style.display='none';
            user_name.style.display='inline';
            empty.classList.remove('content')
            contentright.style.display='block'
            top_story_content_detail_list.style.width='74%'
        }
    });
}


const contentrights=document.getElementsByClassName('content-right')
const top_story_content_detail_lists=document.getElementsByClassName('top-story-content-detail-list')



function showCustomAlert(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}


let top_story_content_footer_button_likes=document.getElementsByClassName('top-story-content-footer-button-like')
let likes=document.getElementsByClassName('like')
for (let i = 0; i < top_story_content_footer_button_likes.length; i++) {
    top_story_content_footer_button_likes[i].addEventListener('click', function () {


        let like_value=top_story_content_footer_button_likes[i].value
        const postIdNum = Number(like_value);
        console.log(postIdNum)
        console.log(window.getComputedStyle(top_story_content_footer_button_likes[i]).color)
        if (window.getComputedStyle(top_story_content_footer_button_likes[i]).color === 'rgba(169, 178, 185, 0.937)') {

            $.ajax({
                url: `/posts/like?postId=${like_value}`,
                type: 'POST',
                data: {postId: postIdNum},
                success: function (result) {
                    showCustomAlert('点赞成功', 3000)
                    top_story_content_footer_button_likes[i].style.color= 'rgba(255,0,0,1)'
                    likes[i].style.color= 'rgba(255,0,0)'
                    console.log('发送点赞请求到:', this.url);
                },
                error: function (error) {
                    showCustomAlert('点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                    console.log(error);
                    console.log('发送点赞请求到:', this.url);
                }

            })

        }else {
            console.log(1111111)
            $.ajax({
                url: `/posts/cancelLike?postId=${like_value}`,

                type: 'POST',
                data: {postId: postIdNum},
                success: function (result) {
                    showCustomAlert('取消点赞', 3000)
                    top_story_content_footer_button_likes[i].style.color = 'rgba(169, 178, 185, 0.937)'
                    likes[i].style.color= 'rgba(169, 178, 185, 0.937)'
                    console.log('发送点赞请求到:', this.url);
                },
                error: function (error) {
                    showCustomAlert('取消点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                    console.log(error);
                    console.log('发送点赞请求到:', this.url);
                }

            })
        }

    })
}
let personalMainPage=document.getElementsByClassName('personalMainPage')[0]
console.log(personalMainPage)
personalMainPage.addEventListener('click',()=>{
    event.preventDefault();
    window.location.href='http://localhost:8080/userHomepage'
})
function articleDetail(postId) {

    console.log( postId)
    const postIdNum = Number(postId);
    $.ajax({
        url: `/postsComments?postId=${postIdNum}`,
        type: 'GET',

        success: function (result) {

            console.log(result)

            let commentListHTML = '';
            const comments = result.comments;
            const commentUsers = result.commentUsers;

            for (let i = 0; i < comments.length; i++) {

                const commentUser = commentUsers[i];
                console.log('commentUser.avatar:', commentUser.avatar);
                console.log('commentUser.username:', commentUser.username);
                console.log('comments[i].content:', comments[i].content);
                console.log('comments[i].createdAt:', comments[i].createdAt);
                commentListHTML += `
                    <div class="comment-item" style="padding-top: 10px;">
                        <div class="comment-user">
                            <img src="${commentUser.avatar}" alt="用户头像" class="avatar">
                            <span class="username">${commentUser.username}</span>
                        </div>
                        <div class="comment-content">
                            <p>${comments[i].content}</p>
                            <span class="comment-time">${comments[i].createdAt}</span>
                        </div>
                        <div class="comment-actions">
                            <span class="reply-icon">💬 回复</span>
                        </div>
                    </div>
                `;
            }

            const comment_item_outer = document.getElementsByClassName('comment-item-outer')[0];
            comment_item_outer.innerHTML += commentListHTML;

        },
        error: function (error) {

            console.log(error);
        }
    })

}

let comments=document.getElementsByClassName('comment-publish')
let top_story_content_footer_button_starts=document.getElementsByClassName('top-story-content-footer-button-start')
for(let i=0;i<top_story_content_footer_button_starts.length;i++){
    top_story_content_footer_button_starts[i].addEventListener('click',()=>{
        if( top_story_content_footer_button_starts[i].innerHTML.includes('收起评论')){
            comments[i].style.display='none'
            let value=top_story_content_footer_button_starts[i].value
            top_story_content_footer_button_starts[i].innerHTML=`<i class="iconfont comment" >&#xe619;</i> ${value}条评论`
        }else{
            top_story_content_footer_button_starts[i].innerHTML=`<i class="iconfont comment" >&#xe619;</i> 收起评论`
            comments[i].style.display='block'
        }





    })
}
document.addEventListener('DOMContentLoaded', function() {
    const pathname = window.location.pathname;
    let temp = 0;
    if (pathname === '/mainPageRecommend') {
        temp = 1

        document.getElementsByClassName('none-input')[0].value = temp
    } else if (pathname === '/mainPageAttention') {
        temp = 2
        document.getElementsByClassName('none-input')[0].value = temp
    } else if (pathname === '/mainPageTrending') {
        temp = 3
        document.getElementsByClassName('none-input')[0].value = temp
    }
})
function publish(postId){
    const postIdNum = Number(postId);
    let content=document.getElementsByClassName('comment-input-detail')[0].value
    let comment_input_detail=document.getElementsByClassName('comment-input-detail')[0]
    $.ajax({
        url:  `/posts/comment?content=${content}&postId=${postId}`,

        type: 'POST',
        data: {postId:postIdNum,
            content:content},


        success: function(result){

            showCustomAlert('评论成功',3000)
            console.log(result);
            comment_input_detail.value=' '
            let commentListHTML = '';
            const comments = result.commentList;
            const commentUsers = result.userList;
            for (let i = 0; i < comments.length; i++) {
                const commentUser = commentUsers[i];
                top_story_content_footer_button_starts[i].innerHTML=`<i class="iconfont comment" >&#xe619;</i> ${result.commentsCount}条评论`
                commentListHTML += `
                    <div class="comment-item" style="padding-top: 10px;">
                        <div class="comment-user">
                            <img src="${commentUser.avatar}" alt="用户头像" class="avatar">
                            <span class="username">${commentUser.username}</span>
                        </div>
                        <div class="comment-content">
                            <p>${comments[i].content}</p>
                            <span class="comment-time">${comments[i].createdAt}</span>
                        </div>
                        <div class="comment-actions">
                            <span class="reply-icon">💬 回复</span>
                        </div>
                    </div>
                `;
            }

            const comment_item_outer = document.getElementsByClassName('comment-item-outer')[0];
            comment_item_outer.innerHTML = commentListHTML;
        },
        error:function(error){
            showCustomAlert('评论失败: ' + error.status + ' ' + error.statusText, 3000);
            console.log(error);

        }

    })
}
let wait_answer=document.getElementsByClassName('wait-answer')[0]
console.log(wait_answer)
wait_answer.addEventListener('click',()=>{
    event.preventDefault();
    window.location.href='/thoughtMainPage'
})
let mainPage=document.getElementsByClassName('mainPage')[0]
mainPage.addEventListener('click',()=>{
    event.preventDefault();
    window.location.href='http://localhost:8080/mainPageRecommend'
})

//显示用户信息
const detailBtn = document.querySelector('.zl');
const userId = detailBtn.dataset.userId;
const url = `http://localhost:8080/admin/toUpdateUserPage?id=${userId}`;
// 使用AJAX获取用户数据
$.ajax({
    dataType: 'json', // 明确指定返回JSON格式
    url:url,
    method: 'GET',
    success: function(user) {
        console.log('获取用户数据成功:', user); // 用于调试
        document.querySelector('.name').textContent = user.user.username;
        document.getElementById('uimg').src= user.user.avatar;
        document.getElementById('userGender').textContent = user.user.gender;
        document.getElementById('userLocation').textContent = user.user.location;
        document.getElementById('userIndustry').textContent = user.user.industry;
        document.getElementById('userBio').textContent = user.user.bio;
        console.log(user.user.gender);
        console.log( user.user.location);
        console.log( user.user.industry);
        console.log(user);
    },
    error: function(error) {
        console.error('AJAX 请求错误:', error);
        alert('网络错误，请重试');
    }
});
//从主页关注
const o_follow_button=document.getElementById("otherfollowers")
o_follow_button.addEventListener('click', function() {
    console.log(111)
    let userId = this.value;
    console.log(userId);
    if (this.classList.contains('unfollows')) {
        // 当前是已关注状态，执行取消关注逻辑
        $.ajax({
            url: `/cancelFollow?id=${userId}`,
            type: 'POST',
            success: function(result) {
                console.log(result)
                showCustomAlert('取消关注成功', 3000);
                follow_button.classList.add('follows');
                follow_button.textContent = '关注';
            },
            error: function(error) {
                showCustomAlert('取消关注失败: ' + error.statusText, 3000);
            }
        });
    }
    else {
        // 当前是未关注状态，执行关注逻辑
        $.ajax({
            url: `/followOthers?id=${userId}`,
            type: 'GET',
            success: function(result) {
                console.log(result)
                showCustomAlert('关注成功', 3000);
                follow_button.classList.add('unfollows');
                follow_button.textContent = '已关注';
            },
            error: function(error) {
                showCustomAlert('关注失败: ' + error.statusText, 3000);
            }
        });
    }
})

//弹窗
function confirms(content, callback) {
    return new Promise((resolve) => {
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'v-modal';
        overlay.style.cssText = 'position: fixed; inset: 0; z-index: 2000; background-color: rgba(0,0,0,0.5);';

        // 创建对话框
        const dialog = document.createElement('div');
        dialog.className = 'el-message-box__wrapper';
        dialog.style.cssText = 'position: fixed; inset: 0; z-index: 2001; display: flex; align-items: center; justify-content: center;';
        dialog.innerHTML = `
      <div class="el-message-box">
        <div class="el-message-box__header">
          <div class="el-message-box__title"><span>系统提示</span></div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__message"><p>${content}</p></div>
        </div>
        <div class="el-message-box__btns">
          <button type="button" class="el-button el-button--default el-button--small cancel-btn">
            <span>取消</span>
          </button>
          <button type="button" class="el-button el-button--default el-button--small el-button--primary confirm-btn">
            <span>确认</span>
          </button>
        </div>
      </div>
    `;

        // 添加到文档
        document.body.appendChild(overlay);
        document.body.appendChild(dialog);

        // 绑定确认按钮事件
        const confirmBtn = dialog.querySelector('.confirm-btn');
        confirmBtn.addEventListener('click', () => {
            removeDialog(overlay, dialog); // 关闭弹窗
            callback(true); // 调用回调并传入结果（true=确认）
        });
        // 绑定取消按钮事件
        const cancelBtn = dialog.querySelector('.cancel-btn');
        cancelBtn.addEventListener('click', () => {
            resolve(false); // 点击取消返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 绑定遮罩层点击事件
        overlay.addEventListener('click', () => {
            resolve(false); // 点击遮罩返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 统一关闭弹窗函数
        function removeDialog(overlay, dialog) {
            overlay.remove();
            dialog.remove();
        }
    });
}
